package com.sky.aspect;

import com.sky.entity.Employee;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Aspect
@Component
@Slf4j
public class AutoFillAspect {
    @Pointcut("@annotation(com.sky.nanotation.AutoFill)")
    public void autoFillPointcut() {
    }
     @Around("autoFillPointcut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        log.info("自动填充注解生效");
        return joinPoint.proceed();
    }
    //before
    @Before("autoFillPointcut()")
    public void before(JoinPoint joinPoint) {
//根据不同的操作类型，自动填充不同的数据
        Object[] args = joinPoint.getArgs();
        //获取操作类型
        OperationType operationType = (OperationType) joinPoint.getArgs()[0];

        //判断参数是否为空
        if (args == null || args.length == 0) {
            return;
        }
//        //判断参数是否为实体类对象
//        if (!(args[0] instanceof Employee)) {
//            return;
//        }

        //准备赋值的数据时间
        LocalDateTime now = LocalDateTime.now();
//        Long currentUserId = BaseContext.getCurrentUserId();

        //根据操作类型判断是否需要自动填充
        if (operationType == OperationType.INSERT) {
            // 自动填充创建时间、更新时间、创建人、更新人
            for (Object arg : args) {
                if (arg instanceof Employee) {
                    Employee employee = (Employee) arg;
                    employee.setCreateTime(now);
                    employee.setUpdateTime(now);
//                    employee.setCreateUser(currentUserId);
//                    employee.setUpdateUser(currentUserId);
                }
            }
        }else if (operationType == OperationType.UPDATE) {
            // 自动填充更新时间、更新人
            for (Object arg : args) {
                if (arg instanceof Employee) {
                    Employee employee = (Employee) arg;
                    employee.setUpdateTime(now);
//                    employee.setUpdateUser(currentUserId);
                }
            }
        }


    }

}
